import axios from 'axios'
import {useEmployeeStore} from '@/stores/modules/employee'
const baseURL = '/api'
import { ElMessage } from 'element-plus'
import router from '@/router'
const instance = axios.create({
  // TODO 1. 基础地址，超时时间
  baseURL,
  timeout:10000
})

//请求拦截器
instance.interceptors.request.use(
  (config) => {
    // TODO 2. 携带token
    const employeeStore=useEmployeeStore()
    if(employeeStore.token){
        config.headers.token=employeeStore.token
    }
    return config
  },
  (err) => Promise.reject(err)
)

//响应拦截器
instance.interceptors.response.use(
  (res) => {
    // TODO 3. 处理业务失败
    // TODO 4. 摘取核心响应数据
    console.log(res);
    
    if(res.data.code==1&& res.status == 200){
        return res
    }
    //处理业务失败
    ElMessage.error(res.data.msg||'服务异常')
    return Promise.reject(res.data)
  },
  (err) => {
    // TODO 5. 处理401错误
    if(err.response?.status===401){
        router.push('/login')
        return Promise.reject(err)
    }
    console.log(err);
    ElMessage.error(/*err.data.msg||*/'服务异常')
    return Promise.reject(err)
  }
)

export default instance
export {baseURL}